//
//  QR_CodeViewController.m
//  EasyToTesco2.0
//
//  Created by 杨森 on 2017/2/9.
//  Copyright © 2017年 EasyToTesco. All rights reserved.
//

#import <Photos/Photos.h>
#import <AssetsLibrary/AssetsLibrary.h>
#import "cooperateRecodeViewController.h"

@interface  QRCodeView: UIView

typedef void (^saveQRCode)();
typedef void (^receiptClick)();

@property (nonatomic, copy) saveQRCode saveQRCode;
@property (nonatomic, copy) receiptClick receiptClick;
@property(nonatomic,strong)UIImageView *qrCodeImg;

@end

@implementation QRCodeView

- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        
        [self setQRCodeView];
    }
    return self;
}

- (void)setQRCodeView
{
    CGFloat marW = 20.f;
    CGFloat ViewW = WIDTH - 2*marW;
    
    self.backgroundColor = [UIColor whiteColor];
//    
    UIView *firstView = [[UIView alloc] initWithFrame:CGRectMake(0,50.f,ViewW,1)];
    firstView.backgroundColor = BACKGROUND_COLOR;
    [self addSubview:firstView];
    
    UILabel *label = [[UILabel alloc] init];
    label.text = @"请用微信扫描二维码完成支付";
    label.font = FONT(15);
    label.textAlignment = NSTextAlignmentCenter;
    [self addSubview:label];
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
       
        make.centerX.equalTo(self.mas_centerX);
        make.bottom.equalTo(firstView.mas_top).offset(-15.f);
    }];
    
    self.qrCodeImg = [[UIImageView alloc] init];
//    _qrCodeImg.image = [UIImage imageNamed:@"shareEasy.jpg"];
    [self addSubview:_qrCodeImg];
    [_qrCodeImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.mas_centerX);
        make.top.equalTo(firstView.mas_bottom).offset(10.f);
        make.width.height.mas_equalTo(ViewW/5*3);
    }];
    
    UIButton *leftbtn = [[UIButton alloc] init];
    [leftbtn setTitle:@"收款账单" forState:UIControlStateNormal];
    leftbtn.titleLabel.font = FONT(15);
    leftbtn.titleLabel.font = [UIFont boldSystemFontOfSize:15];
    [leftbtn setTitleColor:RGB(50, 100, 139) forState:UIControlStateNormal];
    [leftbtn addTarget:self action:@selector(recepitClick) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:leftbtn];
    [leftbtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_qrCodeImg.mas_left);
        make.top.equalTo(_qrCodeImg.mas_bottom).offset(15.f);
        
    }];
    
    
    UIButton *rightbtn = [[UIButton alloc] init];
    [rightbtn setTitle:@"保存图片" forState:UIControlStateNormal];
    rightbtn.titleLabel.font = FONT(15);
    rightbtn.titleLabel.font = [UIFont boldSystemFontOfSize:15];
    [rightbtn setTitleColor:RGB(50, 100, 139) forState:UIControlStateNormal];
    [rightbtn addTarget:self action:@selector(saveQRCodeTophoneClick) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:rightbtn];
    [rightbtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(_qrCodeImg.mas_right);
        make.top.equalTo(_qrCodeImg.mas_bottom).offset(15.f);
        
    }];
    
    
}

//保存图片
- (void)saveQRCodeTophoneClick
{
    if (self.saveQRCode) {
        self.saveQRCode();
    }

}

//收款账单
- (void)recepitClick
{
    if (self.receiptClick) {
        self.receiptClick();
    }

}


@end


#pragma mark  controller

#import "QR_CodeViewController.h"

@interface QR_CodeViewController ()
{
    MBProgressHUD *_progressHUD;
}

@property(nonatomic,strong)NSString *QRCodeStr;

@property(nonatomic,strong)UIImageView *QRCodeImage;

@end

@implementation QR_CodeViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self buildUI];
    [self getQRCodeDataRequest];
}

- (void)viewWillAppear:(BOOL)animated
{
    [self.navigationController setNavigationBarHidden:YES animated:YES];
}

- (void)getQRCodeDataRequest
{
    _progressHUD = [MBProgressHUD show:self.view andMessage:nil];
    [self.view addSubview:_progressHUD];
    
    NSDictionary *params = @{@"username":USERNAME};
    [[NetWorkSharedTools sharedNetWorkTools] objectWithURLDict:params AndMenthodName:@"/api/Business/weixinPayQr" completeBlock:^(id object) {
        
        NSLog(@"%@",object);
        if (JudgeBackDataCode) {
            self.QRCodeStr = [object objectForKey:@"data"];
    
            dispatch_async(dispatch_get_main_queue(), ^{
                [self setQRCodeView];
            });
            
        }
    }];
    
}

- (void)setQRCodeView
{
    [_progressHUD hide:true];
    
    QRCodeView *qrCodeView = [[QRCodeView alloc] initWithFrame:CGRectMake(20.f,100.f,WIDTH-40.f, HEIGHT/2)];
    qrCodeView.layer.masksToBounds = true;
    qrCodeView.layer.cornerRadius = 5.f;
    [qrCodeView.qrCodeImg sd_setImageWithURL:[NSURL URLWithString:self.QRCodeStr]];
    [self.view addSubview:qrCodeView];
    
    __weak typeof(self) weakSelf = self;
    __weak typeof(qrCodeView) weakqrCodeView = qrCodeView;
    qrCodeView.saveQRCode = ^(){

        [weakSelf photoAlbumQX:weakqrCodeView.qrCodeImg.image];
    };
    
    qrCodeView.receiptClick = ^(){
      
        //合作专区
        cooperateRecodeViewController *cooperate = [[cooperateRecodeViewController alloc] init];
        [weakSelf.navigationController pushForm:weakSelf.navigationController pushToAndHidden:cooperate];
    };
    

}


/*
 PHAuthorizationStatusNotDetermined = 0, // 默认还没做出选择
 PHAuthorizationStatusRestricted,        // 此应用程序没有被授权访问的照片数据
 PHAuthorizationStatusDenied,            // 用户已经明确否认了这一照片数据的应用程序访问
 PHAuthorizationStatusAuthorized         //  用户已经授权应用访问照片数据

 */


//相册权限
- (void)photoAlbumQX:(UIImage *)image
{
    PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];

    if (status == PHAuthorizationStatusDenied) {
        //相册权限未开启
        [self showAlertViewToController:self.navigationController];

    }else if(status == PHAuthorizationStatusNotDetermined){
        //相册进行授权
        /* * * 第一次安装应用时直接进行这个判断进行授权 * * */
        [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status){
            //授权后
            if (status == PHAuthorizationStatusAuthorized){
                dispatch_async(dispatch_get_main_queue(), ^{
                    //保存图片
                    [self saveImageToPhotos:image];
                });

            }
        }];
    }else if (status == PHAuthorizationStatusAuthorized){
        
        [self saveImageToPhotos:image];
    }
    

}


//图片保存
- (void)saveImageToPhotos:(UIImage*)savedImage
{
    UIImageWriteToSavedPhotosAlbum(savedImage, self, @selector(image:didFinishSavingWithError:contextInfo:), NULL);

}
//回调
- (void)image: (UIImage *) image didFinishSavingWithError: (NSError *) error contextInfo: (void *) contextInfo
{
    NSString *msg = nil ;
    if(error != NULL){
        msg = @"保存图片失败" ;
    }else{
        msg = @"收款二维码已下载到您的手机相册" ;
    }
    
    MBProgressHUD *hud = [MBProgressHUD showMessage:msg toView:self.view dimBackground:NO AndCompleteBlock:nil];
    [self.view addSubview:hud];
}

-(void)showAlertViewToController:(UIViewController *)controller
{
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    // app名称
    NSString *app_Name = [infoDictionary objectForKey:@"CFBundleDisplayName"];
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提醒" message:[NSString stringWithFormat:@"请在iPhone的“设置->隐私->照片”开启%@访问你的手机相册",app_Name] preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action){
        
    }];
    
    [alert addAction:action1];
    [controller presentViewController:alert animated:YES completion:nil];
}



- (void)buildUI
{
    UIImageView *bgImg = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"bg_QRCodeimg.jpg"]];
    [self.view addSubview:bgImg];
    bgImg.frame = CGRectMake(0, 0,WIDTH, HEIGHT);
    
    UILabel *cenlbl = [[UILabel alloc] init];
    cenlbl.text = @"我要收款";
    cenlbl.font = FONT(16);
    cenlbl.font = [UIFont boldSystemFontOfSize:18];
    cenlbl.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:cenlbl];
    cenlbl.textColor = [UIColor whiteColor];
    [cenlbl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view.mas_centerX);
        make.top.equalTo(self.view.mas_top).offset(35);
        make.width.mas_equalTo(80);
    }];
    
    
    UIButton *backButton = [[UIButton alloc] init];
    [backButton setImage:[UIImage imageNamed:@"jiantou"] forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(regardingBackButtonDidClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:backButton];
    [backButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left).offset(15);
        make.top.equalTo(self.view.mas_top).offset(35);
        make.width.height.mas_equalTo(20);
    }];

}

- (void)regardingBackButtonDidClick
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)dealloc
{
    [_progressHUD removeFromSuperViewOnHide];
}

@end
